package view;

import java.util.Hashtable;

import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;

import controller.CodeController;

public class CodeView extends JComponent implements CellEditorListener {
	private static final long serialVersionUID = 8099801407087846923L;
	private CodeController codeController = CodeController.getInstance();
	private JTable table = new JTable();
	private final int PROGRAM_LINES = 1000;

	public CodeView() {
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.setAlignmentX(LEFT_ALIGNMENT);
		this.add(makeContent());
		editingStopped(null);
	}

	private JComponent makeContent() {
		table.setModel(new CodeTable(PROGRAM_LINES));

		table.getColumnModel().getColumn(0).setPreferredWidth(20);
		table.getColumnModel().getColumn(1).setPreferredWidth(40);
		table.getColumnModel().getColumn(2).setPreferredWidth(150);

		table.getDefaultEditor(String.class).addCellEditorListener(this);

		// Sample Source code!
		table.setValueAt("LOAD foo", 0, 2);
		table.setValueAt("STORE bar", 1, 2);
		table.setValueAt("foo", 2, 1);
		table.setValueAt("3", 2, 2);

		table.setValueAt("bar", 3, 1);

		JScrollPane pane = new JScrollPane(table);
		pane
				.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		pane.setAlignmentX(LEFT_ALIGNMENT);
		return pane;
	}

	@Override
	public void editingCanceled(ChangeEvent e) {
		// nothing to do
	}

	@Override
	public void editingStopped(ChangeEvent e) {
		Hashtable<Integer, String> code = new Hashtable<Integer, String>();
		Hashtable<Integer, String> labels = new Hashtable<Integer, String>();
		CodeTable model = (CodeTable) table.getModel();
		for (int i = 0; i < model.getRowCount(); i++) {
			if (model.getValueAt(i, model.getCodeColumn()) != null) {
				code.put(i, String.valueOf(model.getValueAt(i, model
						.getCodeColumn())));
			}
			if (model.getValueAt(i, model.getLabelColumn()) != null) {
				labels.put(i, String.valueOf(model.getValueAt(i, model
						.getLabelColumn())));
			}
		}
		codeController.setCode(code, labels);
	}
}
